<?php
/*****************************************
 This file is part of the Dynamo CMS UI Toolkit
 Copyright (c) Dynamo Studios 2008

 *** NOTE ***
 Permission is hereby granted to execute this file as a
 web service under the terms of the license agreement.

 See LICENSE.txt, in the system folder.

 All other rights, other than those expressed in the license
 document, are reserved.

 ****************************************/

/**
 * @name Editor Library
 * @version 0.1 (Alvin)
 * @abstract
 * Provides widgets for common editing tasks.
 *
 * @author Sean Micklethwaite
 */
 
 
//include_once(ROOT."public/js/fckeditor/fckeditor_php5.php");

class cUiManager extends cUiForm
/**
* @desc
* The "Manager" is intended for editing discrete, uniform sets of
* data. That is, tables of objects with a uniform structure.
* 
* It is ideally suited for managing content.
* 
* It provides the ability to browse and select multiple items in
* the data set. It provides default buttons for editing, deleting,
* and creating new data.
*/
{
    protected $mTable;
    protected $mAction;
    protected $mEditId;
    protected $mId;

    function __construct($id, $cols, $buttons = array()){
    /**
    * @desc Pre-initializes the Manager widget
    * @param $id		Unique identifier for the widget
    * @param $cols		Array of column headers for the data set
    * @param [$buttons]	Array of custom buttons to add to each row
    */
        $this->mAction = isset($_POST[$id.'-action'])
			? $_POST[$id.'-action'] : $_GET[$id.'-action'];
		$this->mAction = split('-', $this->mAction);

		$this->mEditId = $this->mAction[1];
		$this->mAction = $this->mAction[0];

        $this->mId = $id;


        $myCols = array_merge(array(new cUiCheckbox(), '#'),
            $cols);
        $myCols[] = 'Actions';
        $this->mTable = new cUiTable($myCols, array(
			'id' => $id.'-table',
			'class' => 'UiManager'
		));

        if(!isset($_POST['$$db-count']))
            $_POST['$$db-count'] = 10;
    }

    function CreateBlank(){
    /**
    * @desc Creates a blank form in place of the manager widget
    */
        parent::__construct();
    }

    function CreateForm($num = null){
    /**
    * @desc Generates the Manager widget proper.
    */
        $offset = dbGetOffset();
        $count = dbGetCount();

        $this->AddChild(new cUiFormData(
            '$$db-offset',$offset));
        $this->AddChild(new cUiFormData(
            '$$db-count',$count));

        //
        // Create header + footer button set
        //

        $btnset = new cUiFormItem();

        $btnset->AddChild(new cUiButton(array(
        		'name' => $this->mId.'-action',
        		'value' => 'selAll'
        	),'Select All', 'tick'));
		$btnset->AddChild(new cUiButton(array(
        		'name' => $this->mId.'-action',
        		'value' => 'selAll'
        	),'Clear All', 'cross'));
		$btnset->AddChild(new cUiButton(array(
				'name' => $this->mId.'-action',
				'value' => 'create'
			),'Create New', 'add'));
		$btnset->AddChild(new cUiButton(array(
				'name' => $this->mId.'-action',
				'value' => 'dels'
			),'Delete Selected', 'delete'));



        $navset = new cUiFormItem();


        $navset->AddChild(new cUiButton(array(
				'name' => '$$db-offset',
				($offset == 0) ? 'disabled' : 'value' => 0
				),
				'', 'resultset_first'));
		$navset->AddChild(new cUiButton(array(
				'name' => '$$db-offset',
				($offset < $count) ? 'disabled' : 'value' => $offset - $count
				),
				'', 'resultset_previous'));
        $navset->AddChild("Showing $offset - ".
            (($num) ? (min($count+$offset,$num)." of $num")
            : (($count+$offset)." of dunno")));
		$navset->AddChild(new cUiButton(array(
				'name' => '$$db-offset',
				($num > ($offset+$count)) ? 'value'
				: 'disabled' => $offset + $count
		),'', 'resultset_next'));
		$navset->AddChild(new cUiButton(array(
				'name' => '$$db-offset',
				($num > ($offset+$count)) ? 'value'
				: 'disabled' => ($num % $count == 0)
					? $num - $count : $num - ($num % $count)
		),'', 'resultset_last'));

        $this->AddChild($btnset);
        $this->AddChild($navset);
        $this->AddChild($this->mTable);
        $this->AddChild($navset);
        $this->AddChild($btnset);

        parent::__construct(array(
        	'id' => $this->mId,
        	'class' => 'UiManager'
        ));
        
        //
        // Include script to handle dynamic requests on client side
        //
        
        cUiPage::GetInst()->AddScript('editor');
        cUiPage::GetInst()->AddStartScript($this->mId,
			"new UiManager($('{$this->mId}'));");
    }

    function AddRow($id, $z_data = array(), $zActions = array()){
        $this->mTable->AddChild($r = new cUiTableRow());

        $r->AddChild(new cUiCheckbox());
        $r->AddChild($id);

        foreach($z_data as $field){
            $r->AddChild($field);
        }

        $r->AddChild($actions = new cDycmsClientNode());

        //
        // Create row-specific action buttons
        //

        $actions->AddChild(new cUiButton(array(
				'name' => $this->mId.'-action',
				'value' => 'edit-'.$id,
                'title' => 'Edit'
			),'', 'pencil'));
		$actions->AddChild(new cUiButton(array(
				'name' => $this->mId.'-action',
				'value' => 'del-'.$id,
                'title'=>'Delete'
			),'', 'delete'));

        foreach($zActions as $action){
            // Add custom actions
            $actions->AddChild($action);
        }
    }

    function GetAction(){
        return $this->mAction;
    }
    function GetObjectId(){
        return $this->mEditId;
    }

    function SaveAction(){
        $this->AddChild(new cUiFormData($this->mId.'-action',
            $this->mAction.'-'.$this->mEditId));
    }
}

class cUiToken extends cUiFormItem
{
    function __construct($id, $obj){
        parent::__construct(uiGetIcon('lock').'Security Token');

        $this->AddChild(new cUiSelection(array(
            'id'=>$id.'-token',
            'value'=> $obj->GetTokenType()
            ),array(
            'public' => 'Public',
            'protected' => 'Protected (members only)',
            'private' => 'Private (owners only)',
            'custom' => 'Custom (X-W-R-L)'
        )));

        $this->AddChild(new cUiTextBox(array(
			'name' => $id.'-tokenCustom',
			'value'=>dechex($obj->GetToken())
			), 'Custom'));
    }
}

class cUiTokenEditor extends cUiToken
{
    function __construct($id, $obj){
        parent::__construct($id, $obj);

        $this->AddChild(new cUiButton(array(
            'name'=>$id.'-setToken',
            'value'=>'1'
        ), uiGetIcon('lock_go').'Set'));
    }
}

class cUiOwnershipEditor extends cUiFormItem
{
    function __construct($obj, $argv = array('id'=>'$$uiOwnershipEditor')){
        //
        // Create form
        //

        parent::__construct(uiGetIcon('user').'Owner');
        
		cUiPage::GetInst()->AddScript('editor');
		cUiPage::GetInst()->AddStartScript('UiOwnershipEditor-'.$obj->GetId(),
			uiStdWidgetStartScript('UiOwnershipEditor', 'UiOwnershipEditor-'.$obj->GetId()));
		
		
		//
        // Take ownership, if requested
        //

        switch($uNum = dyPostOrGet($argv['id'].'-ownership-action')){
        	case 'take':
            $obj->TakeOwnership();
			$this->AddChild(new cUiCompletionMsg('You are now the owner of the object.'));
			
            break;
            
			case 'grant':
			
			//
			// Display the user selection box
			//
			
			$this->AddChild(new cUiFormData($argv['id'].'-ownership-action','grant'));
			
			$this->AddChild(new cUiClientSelection(array(
				'name' => $argv['id'].'-ownership-action',
				'value' => $obj->GetOwnerNum()
			)));
			$this->AddChild(new cUiButton(array(
	        ), uiGetIcon('user_go').'Grant'));
			
			return;
			
			
            default:
            if(is_numeric($uNum)){
            	// Interpret as user number
            	$obj->GrantOwnership($uNum);
				$this->AddChild(new cUiCompletionMsg('Set owner successfully.'));
			};
        }

        $user = new cDycmsClient($obj->GetOwnerNum());

        $this->AddChild($user->GetUserName());
        $this->AddChild(new cUiButton(array(
            'name'=>$argv['id'].'-ownership-action',
            'value'=>'take'
        ), uiGetIcon('user_gray').'Take Ownership'));
        $this->AddChild(new cUiButton(array(
            'name'=>$argv['id'].'-ownership-action',
            'value'=>'grant'
        ), uiGetIcon('user_go').'Grant Ownership To...'));
    }
}

class cUiClientSelection extends cUiSelection
{
	function __construct($argv, $zParam = array(), $lbl = null){
		$cls = dbReadAllClients();
		$opts = array();
		
		if($zParam['allowNull']) $opts[0] = '';
		foreach($cls as $client){
			$opts[$client['unum']] = $client['name'];
		}
		
		parent::__construct($argv, $opts, $lbl);
	}
}

class cUiTagEditor extends cUiTextBox
{
	
}

class cUiEditor extends cUiForm
{
	protected $mObject;
	
	function __construct(cDycmsObject &$r_obj)
	{
		parent::__construct(array(
			'method'=>'POST',
			'action'=>dyEditorUrl($r_obj->GetClsId(), $r_obj->GetId()),
			'name'=>'UiEditor-'.$r_obj->GetId(),
			'id'=>'UiEditor-'.$r_obj->GetId(),
			'class' => 'Content'
		));
		
		$this->mObject =& $r_obj;
		
		if($r_obj->Exists()){
			$this->AddChild(new cUiHeading(uiGetIcon($r_obj->GetClass()->GetIcon().'_edit')
				.'Editing '.$r_obj->GetClass()->GetName().': '.$r_obj->GetSummary(), 3,
				array('class' => 'ContentTitle')));
		}else{
			$this->AddChild(new cUiHeading(uiGetIcon($r_obj->GetClass()->GetIcon().'_add')
				.'Editing New '.$r_obj->GetClass()->GetName(), 3,
				array('class' => 'ContentTitle')));
		};
		
		cUiPage::GetInst()->AddMetaData('resultContainer','UiEditor-'.$r_obj->GetId());
		cUiPage::GetInst()->AddScript('editor');
		cUiPage::GetInst()->AddStartScript('UiEditor-'.$r_obj->GetId(),
			uiStdWidgetStartScript('UiEditor', 'UiEditor-'.$r_obj->GetId()));
	}
	
	function AddDefaultButtons(){
	 	$this->AddChild(new cUiButtonSet(array(
 			'type'=>'submit',
 			'name'=>'$$os-editorAction'),
 			$this->mObject->Exists() ? array(
 				'save'=>uiGetIcon('disk').'Save Changes',
 				'saveNew'=>uiGetIcon('report_disk').'Save As New',
 				'pub'=>uiGetIcon('report_go').'Publish',
 				'pubNew'=>uiGetIcon('report_go').'Publish As New',
 				'delete'=>uiGetIcon('delete').'Delete',
 				'preview'=>uiGetIcon('magnifier').'Preview',
 				'view'=>uiGetIcon('magnifier').'View')
				: array(
 				'save'=>uiGetIcon('disk').'Save Changes',
 				'pub'=>uiGetIcon('report_go').'Publish',
 				'preview'=>uiGetIcon('magnifier').'Preview')
			));
 	}
}

class cUiPublisher extends cUiForm
{
	function __construct(cDycmsObject &$r_obj)
	{
		parent::__construct(array(
			'method'=>'POST',
			'action'=>dyEditorUrl($r_obj->GetClsId(), $r_obj->GetId()),
			'name'=>'UiPublisher-'.$r_obj->GetId(),
			'id'=>'UiPublisher-'.$r_obj->GetId()
		));
		
		$this->AddChild(<<<END
<h3 class="publishing">Publishing '{$r_obj->GetSummary()}'</h3>
Enter the following details to make your content reachable.
END
		);
		
		cUiPage::GetInst()->AddMetaData('resultContainer','UiPublisher-'.$r_obj->GetId());
		cUiPage::GetInst()->AddScript('editor');
		cUiPage::GetInst()->AddStartScript('UiPublisher-'.$r_obj->GetId(),
			uiStdWidgetStartScript('UiPublisher', 'UiPublisher-'.$r_obj->GetId()));
	}
	
	function AddDefaultButtons(){
 		$this->AddChild(new cUiButtonSet(array(
 			'type'=>'submit',
 			'name'=>'$$os-editorAction'),
 			array(
 				'doPub'=>uiGetIcon('report_go').'Publish',
 				'edit'=>uiGetIcon('cancel').'Cancel'
 			)));
	}
}

class cUiEditorTextArea extends cDycmsClientNode
{
	protected $msName;
	protected $msValue;
	protected $mEditor = null;

	function __construct($s_name, $s_value, $s_label = null, $b_html = false)
	{
		parent::__construct($s_label);

		$this->msName = $s_name;
		$this->msValue = $s_value;

		if($b_html == true)
		{
			$this->mEditor = new FCKeditor($s_name);
			$this->mEditor->Value = $s_value;
		}
	}

	function DisplayBody()
	{
		if($this->mEditor)
			$this->mEditor->Create();
		else
			echo <<<HTMLEND
	<textarea name="{$this->msName}" class="editor">{$this->msValue}</textarea>
HTMLEND;
	}
}

class cUiEditorMsg extends cUiCompletionMsg
{

}

?>
